<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/12
 * Time: 22:42
 */

namespace App\Models;

use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class Sidebar extends Model
{
    const CACHE_KEY = 'sidebars_list';
    const TABLE_NAME = 'sidebars';
    const SIDEBAR_ROLE = 'sidebar_role';
    /**
     * 与模型关联的数据表
     *
     * @var string
     */
    protected $table = self::TABLE_NAME;

    /**
     * 获得此菜单的角色。
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role', self::SIDEBAR_ROLE, 'sidebar_id', 'role_id');
    }


    public static function getUserSidebarCacheKey(){
        $user = session(User::SESSION_KEY);
        return 'sidebars_'.$user['id'];
    }

    public static function getSidebar()
    {
//        if(!Cache::has(self::getUserSidebarCacheKey())){
            $result = self::getAll();

            //存储用户个人菜单，并打上标签
//            Cache::tags(['sidebars_user'])->put(self::getUserSidebarCacheKey(), $result, 60*24);//一天
//        }else{
//            $result = Cache::get(self::getUserSidebarCacheKey());
//        }

        return $result;
    }

    public static function deleteSidebarCache(){
        //当菜单项所分配的角色变化时
        Cache::tags(['sidebars_user'])->flush();//删除所有用户菜单缓存
    }

    public static function deleteUserSidebarCache(){
        //当前用户分配角色变化时，执行删除
        Cache::forget(self::getUserSidebarCacheKey());
    }

    //全部菜单
    public static function getAll(){

        $sidebars = Sidebar::get();

        $grouped = $sidebars->keyBy('id');
        $grouped = $grouped->toArray();

        //根据个人权限来筛选出菜单项
        $user_cache = session(User::SESSION_KEY);
        $userRole = array_column($user_cache['roles'], 'name');
        if(!in_array('admin', $userRole)){
            //如果不是超级管理员
            $userRoleid = array_column($user_cache['roles'], 'id');
            //该用户对于角色，所拥有的菜单项
            $userRoleofSidebar = DB::table(self::SIDEBAR_ROLE)->whereIn('role_id', $userRoleid)->get()->toArray();
            $userRoleofSidebarId = array_column($userRoleofSidebar, 'sidebar_id');

            foreach ($grouped as $key=>$val) {
                if(in_array($val['id'], $userRoleofSidebarId)){
                    $grouped[$key]['hasRight'] = true;//如果菜单id，属于该用户对应角色中，打上标记
                }
            }
        }
        //根据个人权限来筛选出菜单项

        $result = Sidebar::generateTree2($grouped);

        if(!in_array('admin', $userRole)){
            self::handleRoleSidebar($result);
        }

        Sidebar::arraySortRecursive($result);

        return $result;
    }

    //根据当前用户的角色，来筛选角色所有的菜单项
    public static function handleRoleSidebar(&$sidebars)
    {

        foreach ($sidebars as $key=>$item){
            if(isset($item['hasRight']) && $item['hasRight']){//如果该菜单项有权限，则不遍历其孩子
                continue;
            }

            if(isset($item['child']) && $item['child']){//如果有孩子，则遍历
                self::handleRoleSidebar($sidebars[$key]['child']);
                //孩子遍历完以后，如果发现孩子都没权限，则也将该菜单节点删除
                if(!$sidebars[$key]['child']){
                    unset($sidebars[$key]);
                }
            }else{
                unset($sidebars[$key]);//如果没有，则删除该菜单项
            }
        }
    }

    //无限极分类
    public static function generateTree2($items){
        $tree = array();
        $url = url()->current();
        $path_url = parse_url($url);
        $uri = isset($path_url['path'])?$path_url['path']:'/';

        foreach($items as $key=>$item){

            //和分类无关的处理
            if($uri == $item['url']){
                $items[$key]['isActive'] = true;
            }
            //和分类无关的处理

            if(isset($items[$item['pid']])){
                $items[$item['pid']]['child'][] = &$items[$item['id']];
            }else{
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }


    //无限极分类
    public static function generateTree($items, $selectdId=0){
        $tree = array();

        foreach($items as $key=>$item){

            //和分类无关的处理
            if($selectdId && $item['id'] == $selectdId){
                $items[$key]['selected'] = true;
            }else{
                $items[$key]['selected'] = false;
            }
            //和分类无关的处理

            if(isset($items[$item['pid']])){
                $items[$item['pid']]['child'][] = &$items[$item['id']];
            }else{
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }

    //递归层级排序
    public static function arraySortRecursive(&$items){
        foreach ($items as $item){
            if(isset($item['child']) && $item['child']){
                self::arraySortRecursive($item['child']);
            }
        }
        $res = array_values(array_sort($items, function ($value) {
            return $value['sort'];
        }));
        $items = $res;
    }
}